<?php

/**
 * Created by PhpStorm.
 * User: pangaofeng
 * Date: 16/2/26
 * Time: 上午8:32
 */

/**
 * Class Ueditor
 * Ueditor编辑器
 * @package Vendor\Ueditor
 * @link http://fex.baidu.com/ueditor/
 * @see http://ueditor.baidu.com/
 */
class Ueditor
{
    private $ue_path = '';
    public $hasScript = false;
    /**
     * @var array
     * 请参考ueditor/ueditor.config.js
     */
    private $config = array(
    );

    /**
     * 初始化,可以将Ueidtor路径写入,也可以留空
     * @param string $ue_path
     */
    public function init($ue_path = '')
    {
        if (!$ue_path) {
//            $path = str_replace(array($_SERVER['DOCUMENT_ROOT'], '\\'), array('', '/'), __DIR__);
//            $path = '';
            $this->ue_path = '/Ueditor/ueditor';
        }else{
            $this->ue_path = $ue_path;
        }
    }

    /**
     * 引入JS
     */
    public function includeScript()
    {
        /**
         * 设置一个全局可调用的配置来判断本页面是否已经加载过JS和CSS文件
         */
        if ($this->hasScript)
            return '';
        else {
            $this->hasScript = 1;
            RETURN '
                <script type="text/javascript" src="' . $this->ue_path . '/ueditor.config.js"></script>
                <script type="text/javascript" src="' . $this->ue_path . '/ueditor.all.js"></script>
                <script type="text/javascript" charset="utf-8" src="' . $this->ue_path . '/lang/zh-cn/zh-cn.js"></script>
                <link rel="stylesheet" href="' . $this->ue_path . '/themes/default/css/ueditor.min.css" type="text/css">

            ';
        }
    }

    /**
     * 生成一个编辑器
     * @param string $script_id 字段名
     * @param string $content 要设置的数据
     * @param array $config 配置参数
     */
    public function editor($script_id, $content = '', $config = array())
    {
        $DOC = $this->includeScript();
        if(!empty($config)){
            foreach($config as $k => $v){
                $this->config[$k] = $v;
            }
        }
        RETURN $DOC.'<script id="ueditor_' . $script_id . '" name="' . $script_id . '" type="text/plain">' . $content . '</script>'.
        '<script type="text/javascript">
                    var ueditor_' . $script_id . ' = UE.getEditor("ueditor_' . $script_id . '",' . json_encode($this->config) . ');
            </script>';
    }

}